package ysq.xyg.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.StringUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import ysq.xyg.model.Member;
import ysq.xyg.model.Record;
import ysq.xyg.model.info.BaseUserInfo;
import ysq.xyg.model.info.Page;
import ysq.xyg.model.info.ReturnInfo;
import ysq.xyg.service.BaseUserService;
import ysq.xyg.service.MemberService;
import ysq.xyg.service.RecordService;
import ysq.xyg.util.BaseConstant;
import ysq.xyg.util.BaseUtil;
import ysq.xyg.util.DateUtil;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

/**
 * @author yu sheng qiang
 * @create 2017-04-19 14:15
 **/
@Controller
@RequestMapping("/record")
public class RecordController extends BaseController {

    private static Logger log= LoggerFactory.getLogger(RecordController.class);
    @Resource
    private RecordService recordService;
    @Resource
    private MemberService memberService;
    @Resource
    private BaseUserService baseUserService;
    private Record record;

    @RequestMapping("/listPage")
    public ModelAndView List(HttpServletRequest request, HttpServletResponse response,String menuid){
        return new ModelAndView("/recordList");
    }
    @RequestMapping("/listPageYQ")
    public ModelAndView listPageYQ(HttpServletRequest request, HttpServletResponse response,String menuid){
        return new ModelAndView("/recordListYQ");
    }
    /**
     * 收货人充值
     */
    @RequestMapping("/receivingListPage")
    public ModelAndView receivingListPage(){
        return new ModelAndView("/receivingRecordList");
    }

    @RequestMapping(value = "/JsonList",method = RequestMethod.POST)
    public @ResponseBody JSONObject JsonList(Record record, Page page){
        PageInfo<Record> pageInfo=recordService.pageInfoLeft(record,page.getLimit(),page.getPage());
        JSONObject jsonObject=new JSONObject();
        jsonObject.put("code",0);
        jsonObject.put("msg","");
        jsonObject.put("count",pageInfo.getTotal());
        if(pageInfo !=null && pageInfo.getList() !=null && pageInfo.getList().size() > 0){
            JSONObject row = null;
            JSONArray rows = new JSONArray();
            for(Record item:pageInfo.getList()){
                row=new JSONObject();
                row.put("id",item.getId());
                row.put("memberId",item.getMemberId());
                row.put("type",item.getType());
                row.put("descripts",item.getDescripts());
                row.put("cardNo",item.getCardNo());
                row.put("money",item.getMoney());
                row.put("name",item.getName());
                row.put("headImage",item.getHeadImage());
                if(StringUtil.isNotEmpty(item.getNickName())){
                    row.put("nickName", BaseUtil.decodeBase64(item.getNickName()));
                }
                row.put("phone",item.getPhone());
                row.put("createtime", DateUtil.DateToStr(item.getCreateTime(), DateUtil.DATE_TIME_PATTERN));
                rows.add(row);
            }
            jsonObject.put("data",rows);
        }
        return jsonObject;
    }

    /**
     * 当前登录人查看自己的充值记录
     */
    @RequestMapping(value = "/currentJsonList",method = RequestMethod.POST)
    public @ResponseBody JSONObject currentJsonList(HttpServletRequest request, Record record, Page page){
        BaseUserInfo baseUserInfo = acceptCurrentUser(request);
        record.setUserId(baseUserInfo.getUserid());
        PageInfo<Record> pageInfo=recordService.pageInfoLeft(record,page.getLimit(),page.getPage());
        JSONObject jsonObject=new JSONObject();
        jsonObject.put("code",0);
        jsonObject.put("msg","");
        jsonObject.put("count",pageInfo.getTotal());
        if(pageInfo !=null && pageInfo.getList() !=null && pageInfo.getList().size() > 0){
            JSONObject row = null;
            JSONArray rows = new JSONArray();
            for(Record item:pageInfo.getList()){
                row=new JSONObject();
                row.put("id",item.getId());
                row.put("memberId",item.getMemberId());
                row.put("type",item.getType());
                row.put("descripts",item.getDescripts());
                row.put("money",item.getMoney());
                row.put("name",item.getName());
                row.put("headImage",item.getHeadImage());
                if(StringUtil.isNotEmpty(item.getNickName())){
                    row.put("nickName", BaseUtil.decodeBase64(item.getNickName()));
                }
                row.put("phone",item.getPhone());
                row.put("createtime", DateUtil.DateToStr(item.getCreateTime(), DateUtil.DATE_TIME_PATTERN));
                rows.add(row);
            }
            jsonObject.put("data",rows);
        }
        return jsonObject;
    }

    @RequestMapping(value = "/addRecord",method = RequestMethod.POST)
    public @ResponseBody JSONObject addRecord(HttpServletRequest request, String memberId, double money, String flag) {
        ReturnInfo returnInfo = new ReturnInfo();
        JSONObject jsonObject = new JSONObject();
        if(StringUtil.isEmpty(memberId)||money<1){
            returnInfo = new ReturnInfo(BaseConstant.FAIL, "会员ID不能为空且充值金额最小为1个！");
            jsonObject.put("returnInfo", returnInfo);
            return jsonObject;
        }
        Member member=memberService.selectByPrimaryKey(memberId);
        if(member==null){
            returnInfo = new ReturnInfo(BaseConstant.FAIL,"会员ID不存在！");
            jsonObject.put("returnInfo", returnInfo);
            return jsonObject;
        }
        Record record=new Record();
        record.setId("E"+ BaseUtil.uId());
        if (StringUtils.isNotEmpty(flag) && StringUtils.equals(flag, BaseConstant.BASE_FLAG_TWO)) {
            // 充值人记录
            BaseUserInfo baseUserInfo = acceptCurrentUser(request);
            record.setUserId(baseUserInfo.getUserid());
            Member memberRecord = memberService.selectByPrimaryKey(baseUserInfo.getUserid());
            // 给账户充值
            memberRecord.setMoney(member.getMoney()+money);
            int mid = memberService.updateByPrimaryKey(memberRecord);
            if (mid <= 0) {
                returnInfo = new ReturnInfo(BaseConstant.FAIL,"充值失败！");
                jsonObject.put("returnInfo", returnInfo);
                return jsonObject;
            }
        }
        record.setType(BaseConstant.RECORD_TYPE_CZJL);
        record.setDescripts("充值"+money+"个金额");
        record.setMoney(money);
        record.setMemberId(memberId);
        record.setCreateTime(new Date());
        int id = recordService.insert(record);
        if(id > 0){
            member.setMoney(member.getMoney()+money);
            int mid=memberService.updateByPrimaryKey(member);
            if(mid<=0){
                recordService.deleteByPrimaryKey(record.getId());
                returnInfo = new ReturnInfo(BaseConstant.FAIL,"充值失败！");
                jsonObject.put("returnInfo", returnInfo);
                return jsonObject;
            }
        }else{
            returnInfo = new ReturnInfo(BaseConstant.FAIL,"充值失败！");
            jsonObject.put("returnInfo", returnInfo);
            return jsonObject;
        }
        jsonObject.put("returnInfo", returnInfo);
        return jsonObject;
    }

    @RequestMapping(value = "/selectEntity",method = RequestMethod.GET)
    public ModelAndView SelectEntity(String id){
        ModelAndView view=new ModelAndView("/recordUpdateOrSave");
        record=recordService.selectByPrimaryKey(id);
        view.addObject("record",record);
        return view;
    }

    @RequestMapping(value = "/receivingSelectEntity", method = RequestMethod.GET)
    public ModelAndView receivingSelectEntity(HttpServletRequest request, String id){
        BaseUserInfo baseUserInfo = acceptCurrentUser(request);
        Member member = memberService.selectByPrimaryKey(baseUserInfo.getUserid());
        // 查询出用户的金额
        ModelAndView view = new ModelAndView("/receivingRecordUpdateOrSave");
        record = recordService.selectByPrimaryKey(id);
        view.addObject("record", record);
        view.addObject("member", member);
        return view;
    }
}
